<?php
/**
 * TinyMVC - TinyMVCHttpRequest.class.php file
 * 
 * @author Adrian Wieczorek <adi(at)tinymvc(dot)org>
 * @package TinyMVC
 * @version $Id: TinyMVCHttpRequest.class.php 3 2007-09-11 12:08:07Z adi3ek $
 * 
 */

/**
 * Standard HTTP request handler, with session and cookie support
 * @package TinyMVC
 */
class TinyMVCHttpRequest extends TinyMVCRequest {
	private $serverName;
	private $requestUri;
	private $remoteAddr;
	private $cookieArray;
			
	private function __construct() {
		$this->paramArray = array_merge($_GET, $_POST);
		$this->serverName = $_SERVER['SERVER_NAME'];
		$this->requestUri = $_SERVER['REQUEST_URI'];
		$this->remoteAddr = $_SERVER['REMOTE_ADDR'];		
		$this->cookieArray = $_COOKIE;
		
		// standard PHP session support
		session_start();
		$this->sessionArray = $_SESSION;    
	}

	/**
	 * get instance of class
	 * @return TinyMVCHttpRequest request object
	 */
	static public function getInstance() {
  if(self::$instance == null) {
			self::$instance = new TinyMVCHttpRequest;				
		}
		return self::$instance;
	}
		
	/**
	 * Destructor
	 * @access public  
	 */
	public function __destruct() {
		session_write_close();
	}

	/**
	 * get cookie parameter value by given key
	 * @param string $key parameter key 
	 * @param mixed $nullValue return value for non-existent key
	 * @return mixed parameter value
	 */
	public function getCookieParam($key, $nullValue = null) {
		return array_key_exists($key, $this->cookieArray) ? $this->cookieArray[$key] : $nullValue;
	}
	
	/**
	 * set cookie parameter value
	 * @param string $key parameter key
	 * @param string parameter value
	 */
	public function setCookieParam($key, $value) {
		$this->cookieArray[$key] = $value;
		setcookie($key, $value);
	}
	
	/**
	 * set session parameter
	 * @param string $key session key
	 * @param mixed $value session value 
	 */
	public function setSessionParam($key, $value) {
		parent::setSessionParam($key, $value);
		$_SESSION[$key] = $value;
	}

	/**
	 * Alias of {@link setSessionParam}
	 */
	public function sessionRegister($key, $value) {
		$this->setSessionParam($key, $value);
	}
		
	/**
	 * remove session parameter by key
	 * @param string $key session key
	 */
	public function sessionUnregister($key) {
		parent::sessionUnregister($key);
		unset($_SESSION[$key]);
	}

	/**
	 * get server name
	 * @return string  
	 */
	public function getServerName() {
		return $this->serverName;
	}

	/**
	 * get request URI
	 * @return string
	 */
	public function getRequestUri() {
		return $this->requestUri;
	}
	
	/**
	 * get client's remote address
	 * @return string
	 */
	public function getRemoteAddr() {
		return $this->remoteAddr;
	}
	
	/**
	 * get all cookies
	 * @return array key => value cookie parameters array 
	 */
	public function getCookies() {
		return $this->cookieArray;
	}	
}
